package com.market.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.market.dao.SupplierDao;
import com.market.domain.Picture;
import com.market.domain.Product;
import com.market.domain.Supplier;

@Repository("supplierDao")
public class SupplierDaoJpa extends GenericDaoJpa<Supplier, Long> implements
		SupplierDao {

	public SupplierDaoJpa() {
		super(Supplier.class);
	}

	@Override
	public Supplier save(Supplier supplier) {
		String sql = "update product  set supplier_id = null where supplier_id = "
				+ supplier.getId();
		Query query = this.em.createNativeQuery(sql);
		query.executeUpdate();
		if (supplier.getProducts().size() > 0) {
			sql = "update product set supplier_id = " + supplier.getId()
					+ " where id in (";
			for (Product product : supplier.getProducts()) {
				sql = sql + product.getId() + ",";
			}

			sql = sql.substring(0, sql.length() - 1) + ")"; // remove the last ","
			query = this.em.createNativeQuery(sql);
			query.executeUpdate();
		}
		return super.save(supplier);
	}

	public void remove(Supplier supplier) {
		if (this.findById(supplier.getId()) == null) {
			log.debug(this.getClass() + " Supplier with id " + supplier.getId()
					+ " is not found, can not be deleted");
		} else {
			log.debug(this.getClass() + " Supplier with id " + supplier.getId()
					+ " is found, will be deleted");
			super.removeById(supplier.getId());
		}

	}

	public List<Product> findProducts(Supplier supplier) {
		String sql = "select product.* from product where product.supplier_id ="
				+ supplier.getId();
		Query query = this.em.createNativeQuery(sql, Product.class);
		List<Product> products = query.getResultList();
		return products;

	}

	public List<Picture> findPictures(Supplier supplier) {
		String sql = "select picture.* from picture,supplier_picture where picture.id = supplier_picture.pictures_id "
				+ " and supplier_picture.supplier_id = " + supplier.getId();
		Query query = this.em.createNativeQuery(sql, Picture.class);
		List<Picture> pictures = query.getResultList();
		return pictures;
	}

}
